package com.blogspot.codingandmore.jboss.filter.properties;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import java.util.Vector;

import org.jboss.logging.Logger;

import com.blogspot.codingandmore.jboss.filter.PropertieFactory;
import com.blogspot.codingandmore.jboss.filter.helper.RegExpressionHelper;

/**
 * reads all the properties from a local file in the jboss directory
 * 
 * @author wohlgemuth
 * 
 */
public class FilePropertieFactory extends PropertieFactory {

	private Logger logger = Logger.getLogger(getClass());

	private List<FilterProperties> properties = new Vector<FilterProperties>();

	public static File configuration = new File("ip-filter-config.properties");
	
	public FilePropertieFactory() throws FileNotFoundException, IOException {

		// fill the system with data
		fillConfiguration();

		/**
		 * used to update the configuration all 5 seconds
		 */
		Thread thread = new Thread(new Runnable() {

			public void run() {
				synchronized (properties) {
					try {
						fillConfiguration();
						Thread.sleep(5000);
					} catch (Exception e) {
						logger.warn(e.getMessage(), e);
					}
				}
			}
		});

		thread.start();
	}

	private void fillConfiguration() throws IOException, FileNotFoundException {
		// our comnfiguration file
		File file = configuration;

		if (file.exists() == false) {
			logger.info("creating new config file: " + file.createNewFile());
		}
		logger.info("loading configurations from: " + file.getAbsolutePath());

		properties = RegExpressionHelper.getRegex(file);
	}

	@Override
	public List<FilterProperties> getProperties() {
		return properties;
	}

	@Override
	public boolean permitByDefault() {
		return true;
	}

}
